package com.hisense.ovcloud.warehouse.tool;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class FileTool {

    private final ResourceLoader resourceLoader;

    public FileTool(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    public String readFileFromClasspath(String path, String lineDelimetor) throws IOException {
        var resource = resourceLoader.getResource("classpath:" + path);
        try (var br = new BufferedReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) {
            return br.lines().collect(Collectors.joining(StringUtils.isEmpty(lineDelimetor) ? System.lineSeparator() : lineDelimetor));
        }
    }

    public List<String> readFileFromClasspathToList(String path) throws IOException {
        var resource = resourceLoader.getResource("classpath:" + path);
        try (var br = new BufferedReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) {
            return br.lines().toList();
        }
    }

    public List<String> readFileFromAbsolutePath(String absolutePath) throws IOException {
        return Files.readAllLines(Paths.get(absolutePath));
    }

    public List<byte[]> readFilesToByteArrays(List<String> filePaths) {
        return filePaths.stream()
                .map(path -> {
                    try {
                        // 先按UTF-8读取为字符串，再转为字节数组，确保编码一致性
                        return Files.readString(Paths.get(path), StandardCharsets.UTF_8)
                                .getBytes(StandardCharsets.UTF_8);
                    } catch (IOException e) {
                        throw new RuntimeException("读取文件失败: " + path, e);
                    }
                })
                .collect(Collectors.toList());
    }

    public List<String> readFilesToStringArrays(List<String> filePaths) {
        return filePaths.stream()
                .map(path -> {
                    try {
                        // 先按UTF-8读取为字符串，再转为字节数组，确保编码一致性
                        return Files.readString(Paths.get(path), StandardCharsets.UTF_8);
                    } catch (IOException e) {
                        throw new RuntimeException("读取文件失败: " + path, e);
                    }
                })
                .collect(Collectors.toList());
    }

    public static String readSingleFilesToString(String path) throws IOException {
        return Files.readString(Paths.get(path), StandardCharsets.US_ASCII);
    }
}
